package timgmbh.monopoly.services;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailService {
	
	private Properties props;
	private Session session;
	private Transport transport;
	
	public MailService() throws MessagingException {

		String host="smtp.gmail.com";
		int port=587;
		String user="monopoly.timgmbh@gmail.com";
		String pass="Monopoly1";
		
        props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", port);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");
        //props.put("mail.debug", "true");

        session = Session.getInstance(props, new GMailAuthenticator(user, pass));
        transport=session.getTransport("smtp");
        transport.connect(host, port, user, pass);
	}
	
	public boolean sendMail(String recipient, String subject, String message) {
		try {
			//recipient = "tim11071992@gmail.com";
			
			Message msg = new MimeMessage( session );
			InternetAddress addressFrom = new InternetAddress( "monopoly.timgmbh@gmail.com" );
			msg.setFrom( addressFrom );
			InternetAddress addressTo = new InternetAddress( recipient );
			msg.setRecipient( Message.RecipientType.TO, addressTo );
			msg.setSubject( subject );
			msg.setContent( message, "text/html" );
			Transport.send( msg );
			
			return true;
		} catch (Exception e) {
			System.out.println("ERROR: " + e.getClass() + ": " + e.getMessage());
			return false;
		}
	}
	
	private class GMailAuthenticator extends Authenticator {
	     String user;
	     String pw;
	     public GMailAuthenticator (String username, String password)
	     {
	        super();
	        this.user = username;
	        this.pw = password;
	     }
	    public PasswordAuthentication getPasswordAuthentication()
	    {
	       return new PasswordAuthentication(user, pw);
	    }
	}
}

//------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------
//
//	HOW TO USE:
//

/*try {
	MailService mail = new MailService();
	mail.sendMail("tim11071992@gmail.com", "Testmail", "Das ist ein <a href=\"http://www.google.de\">Test</a>");
} catch (Exception e) {
	System.out.println("ERROR: " + e.getClass() + ": " + e.getMessage());
}*/
